package edu.ynu.se.xiecheng.service;

import edu.ynu.se.xiecheng.entity.Device;
import edu.ynu.se.xiecheng.entity.Greenhouse;
import edu.ynu.se.xiecheng.repository.GreenhouseRepository;
import edu.ynu.se.xiecheng.repository.DeviceRepository;
import edu.ynu.se.xiecheng.repository.SoilDataRepository;
import edu.ynu.se.xiecheng.entity.SoilData;
import edu.ynu.se.xiecheng.dto.GreenhouseDTO;
import edu.ynu.se.xiecheng.dto.DeviceDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.persistence.EntityNotFoundException;
import java.util.List;
import java.util.Optional;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * 大棚信息服务类
 */
@Service
public class GreenhouseService {
    @Autowired
    private GreenhouseRepository greenhouseRepository;
    
    @Autowired
    private DeviceRepository deviceRepository;

    @Autowired
    private SoilDataRepository soilDataRepository;

    /**
     * 查询所有大棚信息
     */
    public List<Greenhouse> findAll() {
        return greenhouseRepository.findAll();
    }

    /**
     * 根据ID查询大棚信息
     */
    public Optional<Greenhouse> findById(Long id) {
        return greenhouseRepository.findById(id);
    }
    
    /**
     * 获取大棚详细信息（包含设备数量）
     */
    public Map<String, Object> getGreenhouseDetail(Long id) {
        Map<String, Object> result = new HashMap<>();
        Greenhouse greenhouse = greenhouseRepository.findById(id)
            .orElseThrow(() -> new EntityNotFoundException("Greenhouse not found"));
        
        // 转换为DTO
        GreenhouseDTO greenhouseDTO = convertToDTO(greenhouse);
        
        // 获取设备数量
        long deviceCount = deviceRepository.countByGreenhouseId(id);
        
        // 获取该大棚所有设备的ID
        List<Long> deviceIds = greenhouse.getDevices().stream()
            .map(Device::getId)
            .collect(Collectors.toList());
        
        // 查询这些设备关联的最新土壤数据
        SoilData soilData = soilDataRepository.findFirstByDeviceIdOrderByCollectTimeDesc(id);
        
        result.put("greenhouse", greenhouseDTO);
        result.put("deviceCount", deviceCount);
        result.put("soilData", soilData);
        return result;
    }

    public GreenhouseDTO findByIdWithDevices(Long id) {
        return greenhouseRepository.findById(id)
            .map(this::convertToDTO)
            .orElseThrow(() -> new EntityNotFoundException("Greenhouse not found"));
    }

    private GreenhouseDTO convertToDTO(Greenhouse greenhouse) {
        GreenhouseDTO dto = new GreenhouseDTO();
        dto.setId(greenhouse.getId());
        dto.setName(greenhouse.getName());
        dto.setArea(greenhouse.getArea());
        dto.setAddress(greenhouse.getAddress());
        dto.setCreateTime(greenhouse.getCreateTime());
        dto.setUpdateTime(greenhouse.getUpdateTime());
        
        List<DeviceDTO> deviceDTOs = greenhouse.getDevices().stream()
            .map(this::convertToDeviceDTO)
            .collect(Collectors.toList());
        dto.setDevices(deviceDTOs);
        
        return dto;
    }

    private DeviceDTO convertToDeviceDTO(Device device) {
        DeviceDTO dto = new DeviceDTO();
        dto.setId(device.getId());
        dto.setDeviceName(device.getDeviceName());
        dto.setDeviceTypeId(device.getDeviceType().getId());
        dto.setDeviceTypeName(device.getDeviceType().getTypeName());
        dto.setStatus(device.getStatus());
        dto.setCreateTime(device.getCreateTime());
        dto.setUpdateTime(device.getUpdateTime());
        return dto;
    }
} 